import LoginApi from "@/common/api/login.js";
import IframeView from "@/views/modules/common/IframeView.vue";
import AppUtil from "../assets/js/AppUtil";
import {TokenUtil} from '@lowcode/jpaas-base-lib';

/**
 * 获取用户与路由菜单信息
 * @returns {Promise<any>}
 */
export const generatorDynamicRouter = (appKey,mainComponent,modules) => {
    return new Promise((resolve, reject) => {
        LoginApi.getLoginUserAndMenu(appKey).then(res => {
            let resourceDto = res.data;
            let sysApp= resourceDto.sysApp;
            let allMenuButtons = resourceDto.buttons;
            let user = resourceDto.currentUser;
            let haveHomePage=false;
            if( resourceDto.portalDef.portId){
                haveHomePage=true;
            }
            //转成树形路由
            let menus = []
            if (resourceDto.menus && resourceDto.menus.length>0){
                menus = resourceDto.menus.filter(menu =>  menu.menuType !== 'F')
            }
            menus=menus.sort((menu1,menu2)=>{return menu1.sn -menu2.sn;});

            if(sysApp && sysApp.isWorkspace==='1') {
                let processMenu = {
                    component: "modules/column/ProcessWorkbench/ProcessWorkbench.vue",
                    menuKey: "ProcessWorkbench",
                    path: "ProcessWorkbench",
                    iconPc: JSON.stringify({
                        "type": "vue3-jpaas-line",
                        "icon": "icon-linegongzuotai"
                    }),
                    id: '34535675321',
                    parentId: '0',
                    settingType:'custom',
                    showType: "URL",
                    name: '流程工作台'
                }
                if (!menus || menus.length === 0) {
                    menus = [processMenu]
                } else {
                    menus.unshift(processMenu)
                }
            }

            let allRouter = buildMenu(menus);
            let routers = [];

            buildRouters(allRouter, routers,`/${appKey}`);
            let obj={
                menus:menus,
                allMenuButtons:allMenuButtons,
                user:user,
                routers:routers,
                haveHomePage:haveHomePage,
                sysApp:sysApp,
                authType : resourceDto.authType
            }
            resolve(obj);
        }).catch(err => {
            reject(err);
        })
    })
}
/**
 * 获取是否有子级菜单
 * 用于过滤掉菜单下的按钮和接口等.
 * @param children 子级菜单
 */
function hasChildMenu(children){
    for (let item of children){
        if((['C','R'].includes(item.menuType))){
            return true;
        }
    }
    return false;
}
/**
 * 构建路由
 * @param menus
 * @param routers
 */
function buildRouters(menus,routers,upPath) {
    for (let item of menus){
        let path = upPath ? `${upPath}/${item.menuKey}`:`/${item.menuKey}`;
        if(item.children && item.children.length > 0){
            //判断子级下是否有菜单
            if(hasChildMenu(item.children)){
                buildRouters(item.children,routers,path);
                continue;
            }
        }
        let component = getComponent(item);
        //判断是否需要拼接token url最后为&accessToken结尾则拼接token
        if (item.params && typeof (item.params) == 'string') {
            let str = item.params.substring(item.params.indexOf("&"));
            if (str === "&accessToken") {
                let accessToken = TokenUtil.getToken();
                if (accessToken) {
                    item.params = item.params + "=" + accessToken;
                }
            }
        }
        let router = {
            name: item.menuKey,
            path,
            component: component,
            meta: {
                menuType: item.menuType,
                params: item.params,
                id: item.id
            }
        };
        routers.push(router);
    }
}

/**
 * 路由懒加载
 * @param view
 * @returns {*}
 */
export function loadView(view,modules){
    if(!view){
        return "";
    }
    let url = view.includes(".vue")?view : view+".vue";
    let component = modules[`/src/views/${url}`]
    return  component;
}

/**
 * 获取组件
 * @param menu
 * @returns {null}
 */
export function getComponent(menu,modules) {
    let component=null;
    if (!menu.settingType || menu.settingType === "iframe") {
        component = IframeView;
    }else if (menu.settingType === "custom" || menu.component) {
        if (typeof menu.component === "function") {
            component = menu.component;
        } else {
            //需要异步加载页面
            component = AppUtil.loadComponent(menu.component,modules,false);
        }
    }
    return component;
}

/**
 * 构建菜单
 * @param rows
 * @returns {*[]}
 */
function buildMenu(rows) {
    let newRows = [];
    rows.forEach(item => {
        if (item.menuType != "F" && item.menuType != "I") {
            newRows.push(item);
        }
    });
    const menus = [];
    buildTree(newRows, menus, '0');
    for (let i = 0; i < menus.length; i++) {
        if (menus[i].children) {
            menus[i].children.sort(compareSn('sn'));
        }
    }
    return menus;
}

/*
 * 将菜单构建成树状
 * @param list
 * @param arr
 * @param parentId
 */
function buildTree(list, arr, parentId) {
    list.forEach(item => {
        if (item.parentId === parentId) {
            let child = {
                title: item.name,
                key: item.menuKey,
                menuKey: item.menuKey,
                id: item.id,
                sn: item.sn,
                icon: item.iconPc,
                showType: item.showType,
                menuType: item.menuType,
                settingType: item.settingType,
                component: item.component,
                layout: item.layout,
                parentModule: item.parentModule,
                params: item.params,
                children: [],
                appType:item.appType
            }
            buildTree(list, child.children, item.id)
            if (child.children.length === 0) {
                delete child.children
            }
            arr.push(child)
        }
    })
}

/**
 * 排序
 * @param property
 * @returns {function(*, *)}
 */
function compareSn(property) {
    return function (obj, obj2) {
        return obj[property] - obj2[property]
    }
}

/**
 * 根据key找到菜单。
 * @param key
 * @param menus
 */
export function getMenuByKey(key,menus){
    let getMenu=function (key,menus){
        let menu;
        for (let i = 0; i <menus.length ; i++) {
            let item=menus[i];
            if(item.key==key){
                menu=item;
                break;
            }else {
                if(item.children&&item.children.length>0){
                    menu=getMenu(key,item.children);
                    if(menu) break;
                }
            }
        }
        return menu;
    }
    let menu=getMenu(key,menus);
    return menu;
}
